package com.huwaiwai001.netty.groupchat;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author 歪大哥😁
 * @date 2020-07-17.
 */
public class GroupChatServer {

    private Selector selector;

    private void read(SelectionKey selectionKey) {
        // 获取channel
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 写出数据到buffer中
        try {
            int readCount = channel.read(buffer);
            if (readCount > 0) {
                // 读取到了数据
                String msg = new String(buffer.array());
                // 输出消息
                System.out.println("from client: " + msg);
                // 转发消息给其他服务器
                sendMsgToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    private void sendMsgToOtherClients(String msg, SocketChannel self) {
        // 获取所有通道
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        for (SelectionKey key : selectionKeys) {
            SelectableChannel channel = key.channel();
            if (channel instanceof SocketChannel && channel != self) {
                SocketChannel sc = (SocketChannel) channel;
                // 写入buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                buffer.flip();
                // 写入数据
                try {
                    sc.write(buffer);
                } catch (IOException e) {
                    try {
                        SocketAddress remoteAddress = sc.getRemoteAddress();
                        System.out.println(remoteAddress);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] args) {

    }
}
